import React, { Component } from 'react'
import axios from "../utils/axios"

// 引入 
import TabTitle from './TabTitle'
import TabCont from './TabCont'


export class Main extends Component {
    constructor(props) {
        super(props)

        this.state = {
            list: [],
            active: 0
        }
    }

    // 请求数据 
    componentDidMount() {
        axios.get("/api/list").then(res => {
            this.setState({
                list: res.data
            })
        })
    }

    // 1）高亮切换
    changeActive(index) {
        this.setState({
            active: index
        })
    }

    // 2）点击添加 
    addTab() {
        const { list } = this.state;
        list.push({
            "id": new Date() * 1,
            "title": "新的tab",
            "cont": "新的tab内容"
        })

        // 重新赋值
        this.setState({
            list: list
        })
    }

    // 3）删除 
    delFn(id) {
        let { list } = this.state;
        list = list.filter( item => {
            return item.id !== id
        })

        this.setState({
            list:list
        })
    }
    render() {
        const { list, active } = this.state;
        return (
            <div className='main'>
                <TabTitle list={list}
                    active={active}
                    changeActive={this.changeActive.bind(this)}
                    addTab={this.addTab.bind(this)}
                    delFn={this.delFn.bind(this)}

                ></TabTitle>
                <TabCont cont={list[active] ? list[active].cont : ""}></TabCont>
            </div>
        )
    }
}

export default Main